package cn._2dland.bots.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn._2dland.bots.TaskManager;
import cn._2dland.bots.U115Bot;
import cn._2dland.bots.jdo.U115AccountManager;
import cn._2dland.bots.jdo.U115BotLogger;
import cn._2dland.bots.jdo.models.U115Account;

@SuppressWarnings("serial")
public class BotAgent extends HttpServlet {
	public static final int ACTION_PICK = 1;
	public static final int ACTION_RENEW = 2;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String aid = req.getParameter("accountID");
		String act = req.getParameter("action");
		try {
			if(aid == null)
				throw new IllegalArgumentException("无效账户ID");
			if(act == null)
				throw new IllegalArgumentException("无效动作");

			Long acctID = Long.valueOf(aid);
			int action = Integer.parseInt(act);

			switch(action){
			case ACTION_PICK:
				pick(acctID);
				break;
			case ACTION_RENEW:
				renew(acctID);
				break;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}
	
	private void pick(Long accountID) throws Exception {
		U115Bot bot = new U115Bot(accountID);

		// 尝试登录，最多重试10次
		for(int failed=0; failed<10 && !bot.login(); failed++);
		if(!bot.isLogin()) {
			// 连续10次登录失败，将账户标记为失败，并退出程序
			U115AccountManager.setStatus(accountID, U115Account.STATUS_ERROR);
			return;
		}

		// 领取空间
		int picked = bot.pick();
		if(picked < 0) {
			// 领取失败时抛出异常，由系统重试
			throw new Exception("领取失败！");
		}
		else if(picked > 0){
			// 正常领取到空间时，进行记录
			U115BotLogger.logPick(accountID, picked);
		}
		TaskManager.createTask(accountID, ACTION_PICK);
	}

	private void renew(Long accountID) throws Exception {
		U115Bot bot = new U115Bot(accountID);

		// 尝试登录，最多重试10次
		for(int failed=0; failed<10 && !bot.login(); failed++);
		if(!bot.isLogin()) {
			// 连续10次登录失败，将账户标记为失败，并退出程序
			U115AccountManager.setStatus(accountID, U115Account.STATUS_ERROR);
			return;
		}
		// 为临时文件续期
		bot.renew(0);
		// 为永久文件续期
		bot.renew(1);

		TaskManager.createTask(accountID, ACTION_RENEW);
	}
}
